# -*- coding: utf-8 -*-
#@@auther Charles_Zhou
import cv2 as cv
import copy
import numpy as np
import random
'''
读取的视频通过高斯模型原理提取视频的前景，并将前景显示出来；
将前景进行目标分割，用不同颜色的矩形框框处，并输出目标的中心位置和面积
'''
videoFilename=r'D:/vtest.avi'
cap = cv.VideoCapture(videoFilename)
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200

while True:
    ret, frame = cap.read()
    #没读到当前帧图像，结束程序
    if not ret:
        break

    fgmask = fgbg.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)
    # fgmask = cv.GaussianBlur(fgmask, (3, 3), 0)
    cv.imshow("background", fgmask)

    bgImage = fgbg.getBackgroundImage()
    _, cnts, _ = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    count = 0
    for c in cnts:
        area = cv.contourArea(c)
        #区域面积小于指定阈值
        if(area < thresh):
            continue
        count += 1
        x, y, w, h = cv.boundingRect(c)
        #通过random.randint生成随机色
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        drawColor = (b, g, r)
        cv.rectangle(frame, (x, y), (x + w, y + h), drawColor, 2)
        print("\n", count, "的中心位置为：（", w / 2, "，",  h / 2, "），面积为：", w * h)
    # print("共检测到", count, "个目标", "\n", "位置为：", w/2, h/2, "面积为：", w*h)
    cv.imshow("frame", frame)
    cv.imshow("Background", bgImage)

    #每一帧暂停50毫秒
    key = cv.waitKey(50)
    #按下ESC键退出
    if key == 27:
        break

cap.release()
cv.destroyAllWindows()


